package itb.fhv.sa.pipesfilters;

public class WordFilter extends Filter implements Runnable {

	private StringBuffer m_currWord;


	public WordFilter(Pipe neighbour) {
		super(neighbour);
		m_neighbour1 = neighbour;
		m_currWord = new StringBuffer();
	}


	/**
	 * Reads Character objects and creates Word objects.
	 * 
	 * @return The created word object.
	 */
	@Override
	public PLOutput read() {
		Word word = null;
		Character plo = (Character) m_neighbour1.read();

		while (plo.getChar() != ' ' && plo.getChar() != '\r'
				&& plo.getChar() != '\n' && plo.getChar() != '\1') {
			m_currWord.append(((Character) plo).getChar());
			plo = (Character) m_neighbour1.read();
		}

		if (plo.getChar() == '\1') {
			m_currWord.append("\1"); // propagate end of file
		}

		if (m_currWord.length() > 0) {
			word = new Word(new String(m_currWord + " "));
			m_currWord = new StringBuffer();
		}

		if (word == null) {
			word = new Word("");
		}

		return word;
	}


	/**
	 * Appends the input Character to the current word. As soon as the end of
	 * the current word is detected, the word is written to the next pipeline
	 * element.
	 */
	@Override
	public boolean write(PLOutput plo) {
		boolean written = false;

		if (((Character) plo).getChar() == ' '
				|| ((Character) plo).getChar() == '\r'
				|| ((Character) plo).getChar() == '\n') {

			if (m_currWord.length() > 0) {
				Word word = new Word(new String(m_currWord));

				while (written == false) {
					written = m_neighbour1.write(word);
				}

				written = false;
				m_currWord = new StringBuffer();
			}

		} else {
			m_currWord.append(((Character) plo).getChar());
		}

		return false;
	}


	@Override
	public void flush() {
		boolean written = false;
		Word word = new Word(new String(m_currWord));

		while (written == false) {
			written = m_neighbour1.write(word);
		}

		written = false;
		m_currWord = new StringBuffer();
		// propagate the end of the data
		m_neighbour1.flush();
	}

}
